<template>
	<div class="select_subject">
 <Cascader v-model="selValue" :data="list" :change-on-select="is_on_select" filterable></Cascader>
</div>
</template>
<script>

export default {
	data:function(){
		return{		
			list:[],
			selValue:[]
		};
	},
	props:{
		value:{
			default:'0'
		},
		field:{
			default:'id'
		},
		is_update:{
			default:false
		},
		has_default:{
			default:0
		},
		is_on_select:{
			default:false
		}
	},
	created:function(){
		this.init(this.value);
		
		this.load_data();
	},
	watch:{
		value(val){
			this.init(val);
		},
		selValue(val){
			
			this.$emit('input',val[val.length-1]);
		},
		is_update(val){
			if(val){
				this.load_data();
			}
		}
	},
	methods:{
		init(val){
			var self = this;
			this.selValue = [];
			for(var i=0;i<self.list.length;i++){
				var arr = [];
				var result = this.get_child_leven(self.list[i],val,arr);
				if(result){
					arr.unshift(self.list[i].value);
					this.selValue = arr;
					break;
				}
			}
			
			
		},
		get_child_leven(item,val,arr){
			
			
			if(item.value==val){
				return true;
			}
			
			if(typeof(item.children)!='object'){
				return false;
			}
			var list = item.children;
			
			for(var i=0;i<list.length;i++){
				var result = this.get_child_leven(list[i],val,arr);
				if(result){
					arr.unshift(list[i].value)
					return true;
				}
			}
			
			return false;
		},
		load_data(){
			var self = this;
			var postdata = {
				is_filter:this.is_update?1:0
			};
			
			Whttp.load('User/Subject/get_types',postdata,function(result){
				var arr = [];
				
				if(self.has_default){
					arr.push({value:'0',label:'不选择'});
				}
				
				
				for(var i=0;i<result.length;i++){
					var ls_list = result[i].list;
					var children = self.get_child(ls_list);
					
					var data = {
						value: result[i][self.field],
						label: result[i].name,
						children: children
					};
					arr.push(data);
				}
			
				self.list = arr;
			});
		},
		get_child(ls_list){
			var self = this;
			var childrens = [];
			if(typeof(ls_list)!='object'){
				return childrens;
			}
			
			for(var j=0;j<ls_list.length;j++){
			
				var data = {
					value: ls_list[j][self.field],
					label: ls_list[j].name
				};
				if(typeof(ls_list[j].children)=='object'){
					data['children'] = this.get_child(ls_list[j].children);
				}
				childrens.push(data);
			}
			
			return childrens;
		}
	}
}
</script>
<style lang="less" scoped>
.select_subject /deep/.ivu-cascader .ivu-cascader-menu-item{ white-space: nowrap;}
</style>